package com.aiyige.page.my.customer;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.api.ApiHelper;
import com.aiyige.base.api.JsonUtil;
import com.aiyige.base.eventbus.EventCustomerChanged;
import com.aiyige.model.CustomerRequestModel;
import com.aiyige.model.request.CustomerInfoUpdateRequest;
import com.aiyige.model.response.ErrorResponse;
import com.aiyige.page.my.customer.dialog.CustomerSexBottomDialog;
import com.aiyige.page.my.customer.dialog.CustomerTypeBottomDialog;
import com.aiyige.page.my.customer.model.CustomerEntity;
import com.aiyige.page.my.customer.model.CustomerType;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.TextWatcherAdapter;
import com.aiyige.utils.ToastX;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.EventBus;

import java.util.Arrays;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 编辑客户资料
 * Created by xiachao on 2018/3/26.
 */
@Track("编辑客户资料")
@Route(path = ARouterConfig.CustomerEditBaseDataPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class CustomerInfoEditPage extends BaseActivity {

    @Autowired
    CustomerEntity customer;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone_number)
    EditText etPhoneNumber;
    @BindView(R.id.tv_customer_type)
    TextView tvCustomerType;
    @BindView(R.id.tv_customer_from)
    TextView tvCustomerFrom;
    @BindView(R.id.et_remark_content)
    EditText etRemarkContent;
    @BindView(R.id.tv_max)
    TextView tvMax;


    public static final int MAX_INTRODUCTION_LENGTH = 500;
    InputNumFilter inputNumFilter;

    InputNumFilter nameInputFilter;

    boolean changed = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_customer);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        initView();
    }


    private void initView() {
        if (customer == null) {
            return;
        }
        tvSex.setText(customer.getSexName());
        etName.setText(customer.getName());
        etName.setSelection(etName.getText().length());//将光标移至文字末尾
        etPhoneNumber.setText(customer.getPhone());
        etPhoneNumber.setSelection(etPhoneNumber.getText().length());
        tvCustomerType.setText(CustomerType.getName(customer.getCustomerType()));
        tvCustomerFrom.setText(customer.getCustomerFrom());
        inputNumFilter = new InputNumFilter(MAX_INTRODUCTION_LENGTH);
        inputNumFilter.setListener(new InputNumFilter.Listener() {
            @Override
            public void inputNum(int num) {
                tvMax.setText(getResources().getString(R.string.text_max, num + "", MAX_INTRODUCTION_LENGTH + ""));
            }
        });
        etRemarkContent.setFilters(new InputFilter[]{inputNumFilter});
        nameInputFilter = new InputNumFilter(14);
        etName.setFilters(new InputFilter[]{nameInputFilter});
        tvMax.setText(getResources().getString(R.string.text_max, 0 + "", MAX_INTRODUCTION_LENGTH + ""));
        etRemarkContent.setText(customer.getRemark());
        etName.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                super.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                changed = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });
        etPhoneNumber.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                super.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                changed = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });

        etRemarkContent.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                super.beforeTextChanged(s, start, count, after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                changed = true;
            }

            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
            }
        });
    }

    private void doRequest() {
        if (TextUtils.isEmpty(getName())) {
            ToastX.show(getResources().getString(R.string.name_can_not_empty));
            return;
        }
        if (TextUtils.isEmpty(getPhone())) {
            ToastX.show(getResources().getString(R.string.phone_can_not_empty));
            return;
        }
        if (getPhone().length() != 11) {
            ToastX.show(getResources().getString(R.string.phone_error));
            return;
        }
//        if (TextUtils.isEmpty(getCustomerType())) {
//            ToastX.show(getResources().getString(R.string.customer_type_can_not_empty));
//            return;
//        }
        if (TextUtils.isEmpty(getCustomerFrom())) {
            ToastX.show(getResources().getString(R.string.customer_from_can_not_empty));
            return;
        }
        showLoading();
        CustomerRequestModel customerRequestModel = CustomerRequestModel.newBuilder().name(getName()).mobile(getPhone()).type(getCustomerType())
                .sex(customer.getSex()).fromChannel(getCustomerFrom()).remark(getRemark()).build();
        CustomerInfoUpdateRequest.newBuilder().id(customer.getId()).customer(customerRequestModel).build().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    hideLoading();
                    if (response.isSuccessful()) {
                        CustomerRequestModel customer = JsonUtil.toObject(response.body().string(), CustomerRequestModel.class);
                        if (customer != null) {
                            EventBus.getDefault().post(EventCustomerChanged.newBuilder().customerRequestModel(customer).build());
                        }
                        finish();
                    } else {
                        ErrorResponse data = JsonUtil.toObject(response.errorBody().string(), ErrorResponse.class);
                        if (data != null) {
                            ToastX.show(data.getMessage());
                        }
                    }
                } catch (Exception e) {
                    ApiHelper.getInstance().failed(this, call, response, e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                hideLoading();
                if (t != null) {
                    ToastX.show(t.getMessage());
                }
            }
        });
    }


    private String getName() {
        return etName.getText().toString().trim();
    }

    private String getPhone() {
        return etPhoneNumber.getText().toString().trim();
    }

    private String getCustomerType() {
        return tvCustomerType.getText().toString().trim();
    }

    private String getCustomerFrom() {
        return tvCustomerFrom.getText().toString().trim();
    }

    private String getRemark() {
        return etRemarkContent.getText().toString().trim();
    }


    @OnClick({R.id.titleBackBtn, R.id.btn_finish, R.id.fl_sex, R.id.fl_customer_type, R.id.rl_customer_from})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                alertDialog();
                break;
            case R.id.btn_finish:
                doRequest();
                break;
            case R.id.fl_sex:
                CustomerSexBottomDialog dialog = CustomerSexBottomDialog.newInstance();
                dialog.setSex(customer.getSex());
                dialog.setListener(new CustomerSexBottomDialog.Listener() {
                    @Override
                    public void onClick(String sex) {
                        changed = true;
                        customer.setSex(sex);
                        tvSex.setText(customer.getSexName());
                    }
                });
                dialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.fl_customer_type:
                // 成交客户、潜在客户、意向客户、失效客户 取消
//                CustomerTypeBottomDialog customerTypeBottomDialog = CustomerTypeBottomDialog.newInstance();
//                customerTypeBottomDialog.setData(Arrays.asList(CustomerType.getName(CustomerType.TRANSACTION_CUSTOMER)
//                ,CustomerType.getName(CustomerType.POTENTIAL_CUSTOMER),CustomerType.getName(CustomerType.INTENTION_CUSTOMER)
//                        ,CustomerType.getName(CustomerType.LOSE_CUSTOMER),getResources().getString(R.string.cancel)));
//                customerTypeBottomDialog.setSelected(CustomerType.getName(customer.getCustomerType()));
//                customerTypeBottomDialog.show(getSupportFragmentManager(),"");
//                customerTypeBottomDialog.setLisenter(new CustomerTypeBottomDialog.Listener() {
//                    @Override
//                    public void onSelect(String value) {
//                        tvCustomerType.setText(value);
//                        customer.setCustomerType(CustomerType.getKey(value));
//                    }
//                });
                break;
            case R.id.rl_customer_from:
                // 其他、电话、来访、转介绍、QQ、微博、自身网站 搜索引擎、中舞网、我的机构星站、外部链接
                CustomerTypeBottomDialog customerFromBottomDialog = CustomerTypeBottomDialog.newInstance();
                customerFromBottomDialog.setData(Arrays.asList(getStr(R.string.other),
                        getStr(R.string.tel),
                        getStr(R.string.come_to_call),
                        getStr(R.string.referral),
                        getStr(R.string.qq),
                        getStr(R.string.weibo),
                        getStr(R.string.website),
                        getStr(R.string.search_engine),
                        getStr(R.string.china_dance_website),
                        getStr(R.string.my_organization_star_site),
                        getStr(R.string.external_links)));
                customerFromBottomDialog.setRecyclerViewHeight(275);
                customerFromBottomDialog.setSelected(customer.getCustomerFrom());
                customerFromBottomDialog.show(getSupportFragmentManager(), "");
                customerFromBottomDialog.setLisenter(new CustomerTypeBottomDialog.Listener() {
                    @Override
                    public void onSelect(String value) {
                        changed = true;
                        tvCustomerFrom.setText(value);
                        customer.setCustomerFrom(value);
                    }
                });
                break;
        }
    }

    private String getStr(int strId) {
        return getResources().getString(strId);
    }

    @Override
    public void onBackPressed() {
        alertDialog();
    }

    private void alertDialog() {
        if (changed) {
            new AlertDialog.Builder(this).setTitle(R.string.the_content_has_not_been_saved_sure_you_want_to_give_up)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        } else {
            finish();
        }

    }
}
